<template>
	<view class="product">
		<view v-on:click="pageClick()">
			<swiper class="banner" v-bind:style="{'height':bnrHeight+'rpx'}" :indicator-dots='true' autoplay='true' :interval='5000'
			 :duration='300' :circular='true'>

				<swiper-item v-if="!image_list.length">
					<image mode="widthFix" v-bind:src="image"></image>
				</swiper-item>

				<block v-for="item,index in image_list">
					<swiper-item>
						<image mode="widthFix" v-bind:src="item.url"></image>
					</swiper-item>
				</block>

			</swiper>


			<view class="price">
				<text class="current-price">
					<block v-if="special>0">￥{{special}}</block>
					<block v-if="!special || special==0">￥{{price}}</block>
				</text>
				<text v-if="special>0" class="old-price">￥{{price}}</text>
				<text class="sale-number">销量：{{sale}}</text>
			</view>
			<view class="name">{{name}}</view>

			<view v-show="pindan && pindan.status==1 && pindan_number" class="pindan-module">

				<view class="head">
					<view class="tit">{{pindan_number}}人正在拼单</view>
					<view class="more">
						<view v-on:click="pindanMore()">查看更多</view>
						<view class="arrow"></view>
					</view>

				</view>

				<view class="list">
					<swiper :autoplay="true" :vertical="true" :duration="500" :circular="true" style="height:200rpx">
						<swiper-item v-for="pindan_swiper_item,index in pindan_swiper">
							<view class="item" v-for="item,index in pindan_swiper_item">
								<view class="customer">
									<image class="photo" v-bind:src="item.headUrl"></image>
									<text class="nickname">{{item.name}}</text>
								</view>

								<view class="pindan-btn">

									<view class="progress">
										<view class="number hide">
											还差 <text class="red">1人</text>拼成
										</view>
										<view class="time">剩余{{item.remaining}}</view>
									</view>
									<view class="go" v-on:click="buy_pindan( item.order_id )">去拼单</view>

								</view>

							</view>
						</swiper-item>


					</swiper>

				</view>
			</view>

			<!-- 商品详情 -->
			<view class="biaoqian">
				<view v-on:click="switch_label('detail')" data-label="detail" class="head-xiangqing " v-bind:class="{'active':label_active=='detail' }">
					商品详情</view>
				<view v-on:click="switch_label('comment')" data-label="comment" class="head-comment " v-bind:class="{'active':label_active=='comment' }">
					商品评论</view>
			</view>
			<view class="detail" v-bind:class="{' hide':label_active!='detail' }">
				<rich-text :nodes="description"></rich-text>
			</view>
			<view class="comment " v-bind:class="{' hide':label_active!='comment' }">

				<view class="item" v-for="item,index in comment_list">
					<view class="author-date">
						<view class="avatar">
							<image mode="widthFix" v-bind:src="item.avatar"></image>
							<text class="author">{{item.author}}</text>
						</view>

						<view class="date">{{item.date}}</view>
					</view>
					<view class="score">
						<view class="star " v-bind:class="[starClass[item.score]]">
							<image mode="widthFix" src="/static/image/skin/star.png"></image>
						</view>
					</view>
					<view class="content">
						{{item.content}}
					</view>
					<view class="img-show">
						<view class="item" v-for="img_item,index in item.img_show">
							<image mode="widthFix" v-bind:src="img_item"></image>
						</view>

					</view>
				</view>

			</view>

			<view class="bottom-panel">
				<view v-on:click="goto_cart()" class="cart">
					<navigator open-type="switchTab" url="/sm_shop/pages/cart/cart">
						<image mode="widthFix" src="/static/image/skin/menu-shopping.png"></image>
						<view v-show="cart_total>0" class="number">{{cart_total}}</view>
					</navigator>
				</view>
				<view v-show="pindan.status!=1" class="button-group">
					<view v-on:click.stop="addCart()" class="add-cart">
						加入购物车
					</view>
					<view v-on:click.stop="buy()" class="buy">立即购买 </view>
				</view>
				<view v-show="pindan.status==1" class="button-group">
					<view v-on:click.stop="buy()" class="add-cart">单独购买</view>
					<view v-on:click.stop="buy_pindan()" class="buy">拼单:￥{{pindan.price}}</view>
				</view>
			</view>

		</view>
		<goods-option
			v-bind:option_panel="option_panel" 
			v-bind:product_id="product_id"
			v-bind:product_image="image" 
			v-bind:price="price"
			v-bind:specification="specification"
			v-bind:spec_object="spec_object"
			v-on:poEvent="poEvent"
		></goods-option>
	</view>
</template>
<script>
	const appInstance = getApp();
	import component_goods_option from '../../common/goods-option';
	export default {
		data: function() {
			return {
				product_id: 0,
				image_list: [],
				image: '',
				description: "",
				name: '',
				price: 0,
				special: 0,
				sale: 0,
				bnrHeight: 0,
				cart_total: 0,

				option_panel: {

					goto: '',
					notice: 0,
					pindan_order: 0, // 主拼单ID

					raw_price: '',
					spec_obj: [],
					show: 0,
				},
				specification: [],
				spec_object: [], // 商品选项列表
				pindan_number: 0,
				pindan: {

				},

				// pindan_list:[],

				pindanPanel: {
					product_id: 0,
					notice: 0,
					show: 0
				},

				pindan_swiper: [
					// [1,2],
					// [3,4],
					// [5]
				],

				comment_list: [],
				starClass: ['', 'one', 'two', 'three', 'four', 'five'],
				label_active: 'detail'
			}
		},
		onLoad: function(options) {

			// #ifdef MP-WEIXIN
			this.insertWxAd();
			// #endif
			this.product_id = options.product_id;
			this.init();

		},
		onShareAppMessage: function (res) {
			// if (res.from === 'button') {
			//   // 来自页面内转发按钮
			//   console.log(res.target)
			// }
			return {
			  title: this.name,
			  path: 'sm_shop/pages/product/product?product_id='+this.product_id
			}
		},
		onShareTimeline:function(){
			return {
			  title: this.name,
			  path: 'sm_shop/pages/product/product?product_id='+this.product_id
			}
		},
		onPullDownRefresh() {
		    console.log('refresh');
			var t = this;
		    setTimeout(function () {
				t.init();
		        uni.stopPullDownRefresh();
		    }, 1000);
		},
		methods: {
			insertWxAd:function(){
				// 在页面中定义插屏广告
				let interstitialAd = null
				
				// 在页面onLoad回调事件中创建插屏广告实例
				if (wx.createInterstitialAd) {
					
				  interstitialAd = wx.createInterstitialAd({
					adUnitId: 'adunit-eed5631518bdd1c6'
				  })
				  
				  interstitialAd.onLoad(() => {console.log('interstitialAd onload')})
				  interstitialAd.onError((err) => {console.log(err)})
				  interstitialAd.onClose(() => {console.log('interstitialAd close')})
				}
				
				// 在适合的场景显示插屏广告
				if (interstitialAd) {
					console.log( 'interstitialAd: show',interstitialAd )
				  interstitialAd.show().catch((err) => {
					console.error(err)
				  })
				}
			},
			init: function() {
				//todo 获取 商品详情
				this.product_detail();
				this.get_spec_object();
				this.cartStatus();
				// this.get_pindan_list(); // 拼单功能暂时注释掉
				this.get_comment_list();

			},
			poEvent: function(e) {

				this.cartStatus();

			},

			/////////////////  以下为自定义方法 /////////////////////////
			product_detail: function(resolve) {

				var product_id = this.product_id;
				var t = this;

				var url = '&r=goods.info';
				var data = {
					'goods_id': product_id
				};

				appInstance.globalData.request(url, data, 'GET', function(res) {
					var bnrHeight = res.data.image_height * 750 / res.data.image_width;
					/* t.setData({
						image_list: res.data.image_list,
						image: res.data.image,
						name: res.data.name,
						price: res.data.price,
						special: res.data.special,
						sale: res.data.sale,
						bnrHeight: bnrHeight,
						description: res.data.description,
						pindan: res.data.pindan
					}); */
					t.image_list = res.data.image_list;
					t.image = res.data.image;
					t.name = res.data.name;
					t.price = res.data.price;
					t.special = res.data.special;
					t.sale = res.data.sale;
					t.bnrHeight = bnrHeight;
					t.description = res.data.description;
					t.pindan = res.data.pindan;

					if (typeof resolve == 'function') {
						resolve(res.data);
					}
				});

			},

			get_spec_object: function(resolve) {

				var product_id = this.product_id;
				var t = this;

				var url = '&r=goods.specification';
				var data = {
					'goods_id': product_id
				};

				appInstance.globalData.request(url, data, 'GET', function(res) {
					/* t.setData({
						specification: res.data.specification,
						spec_object: res.data.spec_object
					}); */
					t.specification = res.data.specification;
					t.spec_object = res.data.spec_object;

					if (typeof resolve == 'function') {
						resolve(res.data);
					}
				});


			},

			buy: function() {
				var t = this;
				appInstance.globalData.checkUserStatus(function(){
					if (t.spec_object.length) {
						// 打开商品规格面板
						t.open_option_panel('buy');
						return;
					}

					// todo 后期商品规格出来后，需加上弹出面板选择
					uni.navigateTo({
						url: '/sm_shop/pages/checkout/checkout?product_id=' + t.product_id
					});
				},1);
				

			},

			buy_pindan: function(order_id) {

				// var order_id = e.currentTarget.dataset.order_id;
				if (this.spec_object.length) {
					// 打开商品规格面板
					this.open_option_panel('buy_pindan', order_id);
					return;
				}

				// todo 后期商品规格出来后，需加上弹出面板选择
				uni.navigateTo({
					url: '/sm_shop/pages/checkout/checkout?product_id=' + this.product_id
				});

			},

			buy_from_pindan_list: function(e) {

				var order_id = e.detail.order_id;
				if (this.spec_object.length) {
					// 打开商品规格面板
					this.open_option_panel('buy_pindan', order_id);
					return;
				}

			},

			get_pindan_list: function(resolve) {

				var t = this;
				var url = 'r=checkout.order.pindan_list&goods_id=' + this.product_id;

				appInstance.globalData.request(url, {}, 'GET', res => {

					var item_arr = [];
					res.data.forEach(function(item) {

						item_arr.push(item);
						if (item_arr.length == 2) {
							t.pindan_swiper.push(item_arr);
							item_arr = [];
						}
					});

					if (item_arr.length > 0) {
						t.pindan_swiper.push(item_arr);
					}

					/* t.setData({

						pindan_swiper: t.data.pindan_swiper,
						pindan_number: res.data.length
					}); */
					t.pindan_number = res.data.length;
					if (typeof resolve == 'function') {
						resolve(res.data);
					}

				});

				var interval = setInterval(function() {

					var now = new Date().getTime();

					t.pindan_swiper.forEach(function(item_group) {
						item_group.forEach(function(item) {
							var start_time = new Date(item.start_time.replace('-', '/')).getTime();
							var end_time = start_time + item.validate_time * 3.6e6;
							var cha = end_time - now;
							if (cha <= 0) {

								clearInterval(interval);
								t.get_pindan_list();
							}
							var days = Math.floor(cha / (24 * 3600 * 1000));

							//计算出小时数
							var leave1 = cha % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
							var hours = Math.floor(leave1 / (3600 * 1000))
							hours = hours < 10 ? '0' + hours : hour;
							//计算相差分钟数

							var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
							var minutes = Math.floor(leave2 / (60 * 1000))
							minutes = minutes < 10 ? '0' + minutes : minutes;
							//计算相差秒数

							var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
							var seconds = Math.round(leave3 / 1000)
							seconds = seconds < 10 ? '0' + seconds : seconds;

							item.remaining = days ? days + '天' : '';
							item.remaining += hours + ':' + minutes + ':' + seconds;
						});

					});

					// t.setData({
					// 	pindan_swiper: t.data.pindan_swiper
					// });

				}, 1000);
			},

			addCart: function(e) {
				appInstance.globalData.checkUserStatus('',1);
				if (this.spec_object.length) {
					// 打开商品规格面板
					this.open_option_panel('add_to_cart');
					return;
				}

				//todo 调用 加入购物车 API
				//todo 监听购物车数据，更改当前购物车数量

				var product_id = product_id;
				var number = number;

				var url = '&r=cart.add';

				var data = {
					product_id: this.product_id,
					number: 1,
				};
				var t = this;
				appInstance.globalData.request(url, data, 'GET', function(res) {

					if (!res.data.status) {
						uni.showToast({
							title: '购物车添加成功',
							icon: 'success',
							duration: 1200
						});

						//todo 更新购物车 状态

						t.cartStatus();
					}



				});

			},

			cartStatus: function(resolve) {


				// todo 获取 购物车 最新状态

				var url = '&r=cart.index';
				var data = {};
				var t = this;
				appInstance.globalData.request(url, data, 'GET', function(res) {

					//todo 刷底部菜单购物车数量值
					var list = res.data.list;

					var cart_total = 0;
					
					if(Array.isArray( list )){
						list.forEach(function(item, index) {
							cart_total += parseInt(item.goods_num);
						});
					}


					// t.setData({
					// 	cart_total: cart_total
					// })
					t.cart_total = cart_total;
					if (typeof resolve == 'function') {
						resolve(res.data);
					}

				});

			},

			goto_cart: function() {


			},

			open_option_panel: function(goto, order_id) {

				this.option_panel.notice++;
				this.option_panel.goto = goto;
				this.option_panel.pindan_order = order_id ? order_id : 0;
				// this.setData({
				// 	option_panel: this.data.option_panel
				// });

			},

			pindanMore: function(e) {

				this.pindanPanel.product_id = this.product_id;
				this.pindanPanel.notice++;
				// this.setData({
				// 	pindanPanel: this.data.pindanPanel
				// });


			},

			// 评论列表
			get_comment_list: function() {

				var url = '&r=goods.comment';
				var data = {
					'goods_id': this.product_id
				};
				var t = this;
				appInstance.globalData.request(url, data, 'GET', function(res) {

					// t.setData({
					// 	comment_list: res.data
					// });
					t.comment_list = res.data;
				});

			},

			switch_label: function(label) {

				// var label = e.currentTarget.dataset.label;

				// this.setData({
				// 	'label_active': label
				// });
				this.label_active = label;
			},

			pageClick: function() {

				this.option_panel.notice--;
				// this.setData({
				// 	option_panel: this.data.option_panel
				// });

			},

		},
		components: {
			'goods-option': component_goods_option
		},
		onPullDownRefresh: function() {
			var p1 = new Promise(this.product_detail);
			var p2 = new Promise(this.get_spec_object);
			var p3 = new Promise(this.cartStatus);
			// var p4 = new Promise(this.get_pindan_list); // 拼单功能暂时注释掉
			var p5 = new Promise(this.get_comment_list);

			var p = Promise.race([p1, p2, p3, p4, p5]);
			p.then(function(result) {
				uni.stopPullDownRefresh();
			});
		}
	}
</script>

<style lang="less">
	@import './product.less';
</style>
